package com.jcl.recruit.searchresume.service;

import com.jcl.core.web.utils.RequestUtils;
import com.jcl.recruit.searchresume.logic.SearchResumeRecordLogic;
import com.jcl.recruit.searchresume.model.SearchResumeRecord;
import com.jcl.recruit.searchresume.vo.SearchResumeRecordVo;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class SearchResumeRecordService {

    @Autowired
    private SearchResumeRecordLogic searchResumeRecordLogic;

    public List<SearchResumeRecord> findList(Integer status) {
        String corpCode = RequestUtils.getCorpCode();
        Integer userId = Integer.parseInt(RequestUtils.getUserId());
        return searchResumeRecordLogic.findList(corpCode, userId, status);
    }


    public SearchResumeRecord findOne(Integer id) {
        String corpCode = RequestUtils.getCorpCode();
        return searchResumeRecordLogic.findOne(corpCode, id);
    }

    public int updateSearchRecord(SearchResumeRecordVo recordVo) {

        String corpCode = RequestUtils.getCorpCode();
        Integer userId = Integer.parseInt(RequestUtils.getUserId());
        SearchResumeRecord record = null;
        if (null != recordVo.getId()) { // update
            record = searchResumeRecordLogic.findOne(corpCode, recordVo.getId());
            if (null == record) {
                return 2;
            }
        }
        List<SearchResumeRecord> oldRecordList = searchResumeRecordLogic.findListByCondition(corpCode,
                userId, recordVo.getKeyword(), recordVo.getCity(), recordVo.getEducation(),
                recordVo.getWorkYear(), recordVo.getWechatPush(), recordVo.getEmailPush());

        if (CollectionUtils.isEmpty(oldRecordList)) {
            if (null == record) { //add
                record = new SearchResumeRecord();
            }
            try {
                PropertyUtils.copyProperties(record, recordVo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (null != recordVo.getId()) { // update
                record.setUpdateTime(new Date());
                searchResumeRecordLogic.update(record);
                return 1;
            } else { //add
                record.setCorpCode(corpCode);
                record.setUserId(userId);
                record.setCreateTime(new Date());
                record.setUpdateTime(new Date());
                record.setKeyword(record.getKeyword().toLowerCase());
                searchResumeRecordLogic.insert(record);
            }
            return 1;
        } else {
            return 0;
        }
    }

    public int deleteById(Integer id) {
        String corpCode = RequestUtils.getCorpCode();
        return searchResumeRecordLogic.deleteById(corpCode, id);
    }

}
